package com.gomore.opple.module.account;

import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gomore.opple.R;
import com.gomore.opple.common.GlobalConstant;
import com.gomore.opple.model.EventDeleteShoppingCar;
import com.gomore.opple.model.EventReflahAddress;
import com.gomore.opple.model.EventReflashShoppingCar;
import com.gomore.opple.model.Good;
import com.gomore.opple.model.ShippingAddress;
import com.gomore.opple.module.BaseFragment;
import com.gomore.opple.module.IntentStart;
import com.gomore.opple.module.account.adapter.AccountAdapter;
import com.gomore.opple.module.account.adapter.AddressAdapter;
import com.gomore.opple.rest.order.OrderBill;
import com.gomore.opple.utils.BigDecimalUtils;
import com.gomore.opple.utils.DensityUtil;
import com.gomore.opple.utils.DialogUtils;
import com.gomore.opple.web.cgform.consumer.entity.TOConsumerEntity;
import com.gomore.opple.web.cgform.order.entity.TOOrderEntity;
import com.gomore.opple.web.cgform.orderdetail.entity.TOOrderdetailEntity;
import com.gomore.opple.web.cgform.shopcart.entity.TOShopcartEntity;
import com.gomore.opple.widgets.MyListView;
import com.gomore.opple.widgets.XCRoundRectImageView;
import com.gomore.opple.widgets.dialog.ConfirmDialog;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;


/**
 * Created by robot
 */
public class AccountFragment extends BaseFragment implements AccountContract.View {
    @Bind(R.id.customer_icon)
    XCRoundRectImageView customer_icon;
    @Bind(R.id.customer_name)
    TextView customer_name;
    @Bind(R.id.customer_mobile)
    TextView customer_mobile;
    @Bind(R.id.customer_company)
    TextView customer_company;
    @Bind(R.id.customer_address)
    TextView customer_address;
    @Bind(R.id.address_my_list_view)
    MyListView address_my_list_view;
    @Bind(R.id.account_my_list_view)
    MyListView account_my_list_view;
    @Bind(R.id.number)
    TextView number;
    @Bind(R.id.total)
    TextView total;
    @Bind(R.id.add_linear)
    LinearLayout add_linear;
    @Bind(R.id.create_order)
    TextView create_order;

    private AccountContract.Presenter mPresenter;
    private Good good;
    private AccountAdapter accountAdapter;
    private AddressAdapter addressAdapter;

    public static AccountFragment getInstance() {
        return new AccountFragment();
    }

    @Override
    protected int getLayoutView() {
        return R.layout.fragment_account;
    }

    @Override
    protected void initalizeData() {
        EventBus.getDefault().register(this);
        if (getArguments() != null && getArguments().getSerializable(IntentStart.GOOD) != null) {
            good = (Good) getArguments().getSerializable(IntentStart.GOOD);
        }
    }

    @Override
    protected void initalizeViews() {
        mPresenter.prepareInitData();
        if (good == null) {
            return;
        }
        number.setText("×" + good.getNumber());
        BigDecimal discount = good.getInputPresent().divide(new BigDecimal(100));
        BigDecimal discountTotal = good.getTotal().multiply(discount);
        if (discount.intValue() == 1) {
            total.setText("¥" + BigDecimalUtils.forMate(discountTotal).toString());
        } else {
            total.setText("¥" + BigDecimalUtils.forMate(discountTotal).toString() +
                    "(" + good.getTotal().toString() + "×" + discount + "折)");
        }
        //地址列表
        addressAdapter = new AddressAdapter(getActivity(), getActivity(), mPresenter.getAddressData());
        address_my_list_view.setAdapter(addressAdapter);
        //购物清单
        accountAdapter = new AccountAdapter(getActivity(), good.getToShopcartEntities());
        account_my_list_view.setAdapter(accountAdapter);
        mPresenter.queryAddress();
    }


    @Override
    public void setPresenter(AccountContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showProgressDialog() {
        DialogUtils.showLoadingDialog(getActivity(), getResources().getString(R.string.loading));
    }

    @Override
    public void hideProgressDialog() {
        DialogUtils.closeLoadingDialog();
    }

    @Override
    public void showMessage(String msg) {
        showToast(msg);
    }


    @Override
    public void showMessage(int msgId) {
        showToast(msgId);
    }

    @Override
    public void ShowConsumer(TOConsumerEntity toConsumerEntity) {
        int height = DensityUtil.dip2px(getActivity(), 80);
        String url = "demo";
        if (toConsumerEntity.getPicture() != null) {
            url = toConsumerEntity.getPicture();
        }
        Glide.with(getActivity())
                .load(url)
                .asBitmap()
                .centerCrop()
                .override(height, height)
                .placeholder(R.mipmap.consumer_icon)
                .into(customer_icon);
        if (toConsumerEntity.getName() != null) {
            customer_name.setText(toConsumerEntity.getName());
        }
        if (toConsumerEntity.getMobile() != null) {
            customer_mobile.setText(toConsumerEntity.getMobile());
        }
        if (toConsumerEntity.getCompany() != null) {
            customer_company.setText(toConsumerEntity.getCompany());
        }
        if (toConsumerEntity.getAddress() != null) {
            customer_address.setText(toConsumerEntity.getAddress());
        }
    }

    @Override
    public void showAddress() {
        addressAdapter.notifyDataSetChanged();
    }

    @Override
    public void goToOrderPay(String orderId) {
        IntentStart.getInstance().startOrderPayActivity(getActivity(), orderId, GlobalConstant.OrderState.UNPAID);
    }

    @Override
    public void deleteShoppingCar() {
        EventDeleteShoppingCar eventDeleteShoppingCar = new EventDeleteShoppingCar();
        eventDeleteShoppingCar.setDeteteShoppingCar(true);
        EventBus.getDefault().post(eventDeleteShoppingCar);
        getActivity().finish();
    }

    @OnClick({R.id.add_linear, R.id.create_order})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.add_linear:
                IntentStart.getInstance().startAddAddressActivity(getActivity(), null);
                break;
            case R.id.create_order:
                saveOrder();
                break;
        }
    }

    public void onEventMainThread(EventReflahAddress eventReflahAddress) {
        if (eventReflahAddress != null && eventReflahAddress.isReflash()) {
            mPresenter.queryAddress();
        }
    }

    private void saveOrder() {
        final OrderBill orderBill = new OrderBill();
        if (mPresenter.getAddressData().size() == 0) {
            showMessage(R.string.add_address);
            return;
        }
        ShippingAddress shippingAddress = null;
        for (int i = 0; i < mPresenter.getAddressData().size(); i++) {
            if (mPresenter.getAddressData().get(i).isSelect()) {
                shippingAddress = mPresenter.getAddressData().get(i);
                break;
            }
        }
        if (shippingAddress == null) {
            showMessage(R.string.select_address);
            return;
        }
        TOOrderEntity toOrderEntity = new TOOrderEntity();
        toOrderEntity.setOrderTime(new Date());
        toOrderEntity.setStoreNumber(mPresenter.getUser().getStoreCode());
        toOrderEntity.setReceiverAddress(shippingAddress.getAddress());
        BigDecimal discount = good.getInputPresent().divide(new BigDecimal(100));
        BigDecimal discountTotal = good.getTotal().multiply(discount);
        toOrderEntity.setOrderPrice(BigDecimalUtils.forMate(discountTotal));
        toOrderEntity.setGoodsNum("" + good.getNumber());
        toOrderEntity.setProvince(shippingAddress.getProvince());
        toOrderEntity.setCity(shippingAddress.getCity());
        toOrderEntity.setCountry(shippingAddress.getCountry());
        toOrderEntity.setReceiverName(shippingAddress.getName());
        toOrderEntity.setReceiverMobile(shippingAddress.getMiblephone());
        toOrderEntity.setConsumerId(shippingAddress.getConsumerId());
        toOrderEntity.setIsSuccessSend(false);
        toOrderEntity.setGuideId(mPresenter.getUser().getEmployee().getId());
        toOrderEntity.setOrderState(GlobalConstant.OrderState.UNPAID);
        orderBill.setOrder(toOrderEntity);
        List<TOOrderdetailEntity> toOrderdetailEntityList = new ArrayList<>();
        for (int j = 0; j < good.getToShopcartEntities().size(); j++) {
            TOShopcartEntity toShopcartEntity = good.getToShopcartEntities().get(j);
            TOOrderdetailEntity toOrderdetailEntity = new TOOrderdetailEntity();
            toOrderdetailEntity.setRemark(toShopcartEntity.getGoods().getSize());
            toOrderdetailEntity.setGoodsCover(toShopcartEntity.getGoods().getPictures());
            toOrderdetailEntity.setGoodsName(toShopcartEntity.getGoods().getName());
            toOrderdetailEntity.setGoodsSpec(toShopcartEntity.getGoods().getSpec());
            toOrderdetailEntity.setGoodsUnit(toShopcartEntity.getGoods().getUnit());
            toOrderdetailEntity.setGoodsBrand(toShopcartEntity.getGoods().getBrandId());
            toOrderdetailEntity.setGoodsNum("" + toShopcartEntity.getGoodsNum());
            toOrderdetailEntity.setGoodsPrice(toShopcartEntity.getCostPrice());
            toOrderdetailEntity.setGoodsId(toShopcartEntity.getGoodsId());
            toOrderdetailEntity.setGoodsCode(toShopcartEntity.getGoods().getCode());
            toOrderdetailEntityList.add(toOrderdetailEntity);
        }
        orderBill.setOrderdetailList(toOrderdetailEntityList);
        //确定框
        ConfirmDialog.onNoOnclickListener onNoOnclickListener = null;
        ConfirmDialog.onYesOnclickListener onYesOnclickListener = null;
        final String title = "提示";
        String message = "确定生成订单吗?";
        onYesOnclickListener = new ConfirmDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                mPresenter.saveOrder(orderBill);
            }
        };
        onNoOnclickListener = new ConfirmDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                DialogUtils.cancel();
            }
        };
        DialogUtils.showConfirmDialog(getActivity(), onYesOnclickListener, onNoOnclickListener, title, message);
    }

    @Override
    public void onLeftIconClick() {
        EventReflashShoppingCar eventReflashShoppingCar = new EventReflashShoppingCar();
        eventReflashShoppingCar.setReflashShoppingCar(true);
        EventBus.getDefault().post(eventReflashShoppingCar);
        super.onLeftIconClick();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
